#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

#define GLBMP_INTERNAL
#include "glbmp.h"
#define GLBMP_INTERNAL_USED

static int
open_bmp_file(const char *fpath, FILE **bmp_file)
{
    char bftype[2];

    *bmp_file = fopen(fpath, "r");

    bftype[0] = fgetc(*bmp_file);
    bftype[1] = fgetc(*bmp_file);

    if ((bftype[0] != 'B') && (bftype[1] != 'M')) {
        return 1;
    } else {
        return 0;
    }
}

static int
close_bmp_file(FILE *file)
{
    int errco = fclose(file);

    if (!errco) {
        printf("[NOTIFY] file closed without issue\n");
    }

    return errco;
}

static GLBMP_bmp_headers*
alloc_headers()
{
    size_t hdrsize = sizeof(GLBMP_bmp_headers);
    printf("[NOTIFY] headers size: %lu bytes\n", hdrsize);
    return malloc(hdrsize);
}

static int
load_bmp_headers(FILE *bmp_file, GLBMP_bmp_headers *headers)
{
    rewind(bmp_file);

    headers->fhead.bfType[0] = fgetc(bmp_file);
    headers->fhead.bfType[1] = fgetc(bmp_file);

    if (strncmp(headers->fhead.bfType, "BM", 2) != 0) {
        return 1;
    }

    printf("[NOTIFY] BM type declared by file\n");

    return 0;
}

static int
discard_bmp_headers(GLBMP_bmp_headers *headers)
{
    free(headers);
    printf("[NOTIFY] headers freed\n");
    return 0;
}

void
GLBMP_print_headers(const char *fpath)
{
    FILE *bmp_file;
    GLBMP_bmp_headers *headers;

    int errco = open_bmp_file(fpath, &bmp_file);
    if (errco) {
        fprintf(stderr, "[ERROR] BAD FILE\n");
        goto TERMINATE;
    }
    headers = alloc_headers();
    errco += load_bmp_headers(bmp_file, headers);
    if (errco) {
        fprintf(stderr, "[ERROR] headers not compliant\n");
    } else {
        printf("[NOTIFY] headers read without issue\n");
    }
    errco += discard_bmp_headers(headers);
TERMINATE:
    errco += close_bmp_file(bmp_file);

    printf("[NOTIFY] errors encountered: %x\n", errco);
}

